﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using ImageGallery.DAL;
using Telerik.Web.UI;

public partial class _Details : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //get the query string for the initial image if it exists
            int photoId = 0;
            IQueryable<Photo> allImages = PhotoDAO.GetAll();
            object PhotoIdQs = Request.QueryString["PhotoID"];
            if (PhotoIdQs != null) Int32.TryParse(PhotoIdQs.ToString(), out photoId);
            

            //there isn't an image with this ID in the DB (the querystring is somehow wrong)
            //so we reset the photoId to 0, later code will handle it
            if (PhotoDAO.GetPhotoById(photoId) == null) photoId = 0;
           
            //photoId is still 0 - something with the querystring was wrong
            //either could not be parsed, or no photo with this id
            //so we select the first photo
            if (photoId == 0) photoId = allImages.ElementAt<Photo>(0).PhotoID;

            
            //store the currently shown photoId for later use (updating the details and rating)
            Session["currentPhotoId"] = photoId;

            //create the ShareUrl and descriptions on initial page load
            updateDetails(photoId);

            rotatorImagesList.DataSource = allImages;
            rotatorImagesList.DataBind();

        }
    }

    protected void rotatorImagesList_ToggleSelectedPhoto(object sender, RadRotatorEventArgs e)
    {
        //set alt and filename for the images in the rotator
        string pictureName = (e.Item.DataItem as Photo).Title;
        if (pictureName != string.Empty && pictureName != null)
        {
            pictureName = pictureName.Replace(" ", "_");
        }
        else
        {
            pictureName = Guid.NewGuid().ToString();
        }
         pictureName += "_thumb";
        RadBinaryImage thumbnail = (e.Item.FindControl("binaryImageThumbnail") as RadBinaryImage);
        thumbnail.AlternateText = pictureName;
        thumbnail.SavedImageName = pictureName;

        //preselect the needed photo in the Rotator on the initial page load
        if ((e.Item.DataItem as Photo).PhotoID == (int)Session["currentPhotoId"])
        {
            string script = "var indexToSelect = " + e.Item.Index + ";Sys.Application.add_load(selectInitialItem);";
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "toggleInitialSelectedItem", script, true);
        }
    }

    protected void rotatorImagesList_SelectImage(object sender, RadRotatorEventArgs e)
    {
        int photoId = Int32.Parse((e.Item.FindControl("hiddenFieldPhotoIdContainer") as HiddenField).Value);
        Session["currentPhotoId"] = photoId;
        updateDetails(photoId);
    }

    protected void updateDetails(int photoId)
    {
        Photo currentPhoto = PhotoDAO.GetPhotoById(photoId);

        binaryImageFullImage.DataValue = currentPhoto.Data;
        string pictureName = currentPhoto.Title;
        if (pictureName != string.Empty && pictureName != null)
        {
            pictureName = currentPhoto.Title.Replace(" ", "_");
        }
        else
        {
            pictureName = Guid.NewGuid().ToString();
        }
        binaryImageFullImage.SavedImageName = pictureName;
        binaryImageFullImage.AlternateText = pictureName;

        labelImageTitle.Text = currentPhoto.Title;
        labelImageLocation.Text = currentPhoto.Location;
        labelImageDescription.Text = currentPhoto.Description;

        ratingRateImage.DbValue = currentPhoto.Rating;
        labelImageRating.Text = string.Format("{0:f2}", currentPhoto.Rating);

        string sharedUrl = "Details.aspx?PhotoID=" + currentPhoto.PhotoID.ToString();
        socialShareNetworkShare.UrlToShare = "~/" + sharedUrl;
        textBoxCopyUrl.Text = socialShareNetworkShare.UrlToShare;
        socialShareNetworkShare.TitleToShare = currentPhoto.Title;
    }
    protected void ratingRateImage_Rate(object sender, EventArgs e)
	{
		Photo currentPhoto = PhotoDAO.GetPhotoById((int)Session["currentPhotoId"]);
		int? ratesCount = currentPhoto.RatesCount;
		float? rating = currentPhoto.Rating;
		float? newRating = 0f;
        float selectedRating = (float)ratingRateImage.Value;


		if (!MyRatings.ContainsKey(currentPhoto.PhotoID)) // a check whether the user has already rated the current photo
		{
			newRating = (selectedRating + rating * ratesCount) / (ratesCount + 1); // the new rating of the picture is calculated
			ratesCount++; // the count of the rates is raised
		}
		else
		{
			// the user's last rate is overriden by the new one and the current photo rating is recalculated
			float? ratingsSum = ratesCount * rating;
			float? ratingsSumBeforeLastVote = ratingsSum - MyRatings[currentPhoto.PhotoID];
			newRating = (ratingsSumBeforeLastVote + selectedRating) / ratesCount;
		}

		MyRatings[currentPhoto.PhotoID] = selectedRating;


        ratingRateImage.DbValue = newRating;
        labelImageRating.Text = string.Format("{0:f2}", newRating);

		currentPhoto.Rating = newRating;
		currentPhoto.RatesCount = ratesCount;
		PhotoDAO.UpdatePhoto(currentPhoto);


	}

	public Dictionary<int, float> MyRatings
	{
		get
		{
			if (Object.Equals(Session["MyRatings"], null))
			{
				Session["MyRatings"] = new Dictionary<int, float>();
			}
			return Session["MyRatings"] as Dictionary<int, float>; 
		}
		set
		{
			Session["MyRatings"] = value;
		}
	}

    protected void ClearVotingDataFromSession(object sender, EventArgs e)
    {
        Session["MyRatings"] = null;
    }
}
